import { createStore } from "vuex";
import Cookies from "js-cookie";

const store = createStore({
  state: {
    user: null,
    role: null,
    showToast: false,
    toastMessage: "",
  },
  mutations: {
    setUser(state, user) {
      state.user = user;
      state.role = user.role;
    },
    clearUser(state) {
      state.user = null;
      state.role = null;
    },
    showToast(state, { message, type }) {
      state.showToast = true;
      state.toastMessage = message;
      console.log("Toast shown:", message); // 调试信息
    },
    hideToast(state) {
      state.showToast = false;
      state.toastMessage = "";
      console.log("Toast hidden"); // 调试信息
    },
  },
  actions: {
    login({ commit }, user) {
      commit("setUser", user);
    },
    logout({ commit }) {
      commit("clearUser");
      Cookies.remove("user"); // 清除 cookie
    },
    showToast({ commit }, { message, type }) {
      commit("showToast", { message, type });
      setTimeout(() => {
        commit("hideToast");
      }, 3000); // 自动隐藏提示
    },
  },
  getters: {
    isAuthenticated(state) {
      return !!state.user;
    },
    userRole(state) {
      return state.role;
    },
    showToast(state) {
      return state.showToast;
    },
    toastMessage(state) {
      return state.toastMessage;
    },
  },
});

export default store;
